/*
* 新增作业许可
* */

import 'dart:typed_data';

import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_input_widget.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:center_beijing/widgets/selectRow_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'dart:io';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';

class AddWorkPermit extends StatefulWidget {
  AddWorkPermit();

  @override
  _AddWorkPermitState createState() => _AddWorkPermitState();
}

class _AddWorkPermitState extends State<AddWorkPermit> {
  final TextEditingController projectName = TextEditingController(); //工程名称
  final TextEditingController projectName2 = TextEditingController(); //分部分项工程名称
  final TextEditingController contentController = TextEditingController(); //施工内容

  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var ids = Go.Get.arguments;
  var detail = Map();

  var apply_time = ''; //申请时间
  var plan_time = ''; //计划施工时间

  List workList = []; //检查项列表

  Uint8List _paint; //签名
  List<Media> photos = [];
  ImageForm.FormData formData;
  List passPhoto = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getWorkList();
    if(ids!=null){
      this.getDetail();
    }
  }


  /*
  * 获取详情
  * */
  getDetail() async {
    var result = await getConsWorkLicenseEx({
      'id': ids['businessId'],
    });
    if (result != null && result.length > 0) {
      this.setState(() {
        apply_time = result['applyTimeStr'];
        plan_time = result['planWorkTimeStr'];
        this.projectName.text = result['projectName'];
        this.projectName2.text = result['partProjectName'];
        contentController.text = result['workContent'];
      });
    }
  }

  getWorkList() async {
    var result = await getWorkCheckLicDefList({
      'projectSectionId': GlobalConfig.selectFactory.tag,
    });
    if (result != null && result.length > 0) {
      this.setState(() {
        workList = result;
      });
    }
  }

  submit() async {
    var pass = {
      'item': jsonEncode({
        'projectSectionId': GlobalConfig.selectFactory.tag,
        'projectName': projectName.text,
        'partProjectName': projectName2.text,
        'workContent': contentController.text,
        'startTime': plan_time,
        'endTime': plan_time,
        'applyTime': apply_time,
        'planWorkTime': plan_time,
      }),
      'workLicenseResults': jsonEncode(workList
          .map((e) => {
                'checkResult':
                    e['selectType'] != null ? e['selectType'].label : '合格',
                'checkContent': e['checkContent']
              })
          .toList()),
      'signId': this.passPhoto[0]['attachmentId']
    };
    if(ids!=null&&ids['taskKey']=='license_start'){
      pass['taskId'] = ids['taskId'];
    }
    print(pass);
    var result = await saveConsWorkLicense(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '提交成功');
      Go.Get.back(result: '成功');
      bus.emit('refreshHome');
    }
  }

  Future addImage() async {
    this.passPhoto = [];

    loading.show(delay: 30);
    if (_paint != null) {
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      formData.files.add(MapEntry(
          "files",
          await ImageForm.MultipartFile.fromBytes(_paint,
              filename: "bbq.jpg", contentType: MediaType('image', 'png'))));

      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        this.passPhoto = result;
      }
    }
    this.submit();
  }

  justifyInfo() {
    if (projectName.text == '') {
      Fluttertoast.showToast(msg: '请输入工程名称');
      return false;
    } else if (projectName2.text == '') {
      Fluttertoast.showToast(msg: '请输入分项工程名称');
      return false;
    } else if (contentController.text == '') {
      Fluttertoast.showToast(msg: '请输入施工内容');
      return false;
    } else if (this._paint == null) {
      Fluttertoast.showToast(msg: '请申请人签字');
      return false;
    } else if (apply_time == '') {
      Fluttertoast.showToast(msg: '请选择申请时间');
      return false;
    } else if (plan_time == '') {
      Fluttertoast.showToast(msg: '请选择计划施工时间');
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Styles.MainBackgroundColor,
        appBar: AppBar(
          title: Text('施工作业许可'),
        ),
        body: SafeArea(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 40),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    color: Colors.white,
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '基本信息',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8, Styles.spacing8, 0, 0),
                          child: CustomInput(
                            textAlign: TextAlign.right,
                            titleColor: Styles.TitleColor,
                            inputformat: [
                              LengthLimitingTextInputFormatter(10),
                            ],
                            title: '工程名称',
                            placeHold: '请输入',
                            textInput: this.projectName,
                            clearAll: false,
                            require: true,
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8, Styles.spacing8, 0, 0),
                          child: CustomInput(
                            textAlign: TextAlign.right,
                            titleColor: Styles.TitleColor,
                            inputformat: [
                              LengthLimitingTextInputFormatter(10),
                            ],
                            title: '分部分项工程名称',
                            placeHold: '请输入',
                            textInput: this.projectName2,
                            clearAll: false,
                            require: true,
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          margin: EdgeInsets.fromLTRB(Styles.spacing8,
                              Styles.spacing8, Styles.spacing8, 0),
                          // padding: EdgeInsets.fromLTRB(
                          //     Styles.spacing8, 0, Styles.spacing8, 0),
                          child: TextAreaWidget(
                            maxLength: 100,
                            labelText: '施工内容',
                            defaultValue: '',
                            placeholder: '请输入',
                            disabled: false,
                            required: true,
                            rows: 2,
                            textController: contentController,
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text.rich(TextSpan(children: [
                                TextSpan(
                                    text: '*',
                                    style: TextStyle(
                                        fontSize: Styles.MiddleFont17,
                                        color: Styles.RedColor)),
                                TextSpan(
                                    text: '申请人',
                                    style: TextStyle(
                                        fontSize: Styles.MiddleFont17,
                                        color: Styles.TitleColor)),
                              ])),
                              GestureDetector(
                                onTap: () async {
                                  print('签名');
                                  var result =
                                      await Go.Get.toNamed(RouteConfig.sign);
                                  if (result != null) {
                                    _paint = result;
                                  }
                                  this.setState(() {});
                                },
                                child: Container(
                                  child: _paint != null
                                      ? Image.memory(
                                          _paint,
                                          width: 80.w,
                                          height: 30.h,
                                        )
                                      : Icon(
                                          Icons.mode_edit,
                                          color: Styles.BlueColor,
                                          size: Styles.MiddleFont17,
                                        ),
                                ),
                              )
                            ],
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                          padding:
                              EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                          child: SelectRow(
                              bottomLine: true,
                              titleColor: Styles.TitleColor,
                              require: true,
                              selectType: DateMode.YMD,
                              title: '申请时间',
                              rightText: apply_time,
                              selectCallback: (value) {
                                this.setState(() {
                                  apply_time = value;
                                });
                              }),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                          padding:
                              EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                          child: SelectRow(
                              titleColor: Styles.TitleColor,
                              require: true,
                              selectType: DateMode.YMD,
                              title: '计划施工时间',
                              rightText: plan_time,
                              selectCallback: (value) {
                                this.setState(() {
                                  plan_time = value;
                                });
                              }),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(top: Styles.spacing16),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '作业条件确认',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: workList.length,
                          itemBuilder: (BuildContext context, int index) {
                            //条目构建函数传入了index,根据index索引到特定图片
                            return Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom: BorderSide(
                                          color: Styles.SpatLineColor,
                                          width: 1))),
                              padding: EdgeInsets.fromLTRB(Styles.spacing16,
                                  Styles.spacing16, Styles.spacing16, 0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text.rich(TextSpan(children: [
                                    TextSpan(
                                        text: "${(index + 1).toString()}、",
                                        style: TextStyle(
                                            color: Styles.BlackColor,
                                            fontSize: Styles.Middle15Font)),
                                    TextSpan(
                                        text:
                                            "${workList[index]['checkContent']}",
                                        style: TextStyle(
                                            color: Styles.BlackColor,
                                            fontSize: Styles.Middle15Font)),
                                  ])),
                                  Container(
                                    alignment: Alignment.centerLeft,
                                    color: Colors.white,
                                    child: CustomRadio(
                                      currentItem:
                                          workList[index]['selectType'] != null
                                              ? workList[index]['selectType']
                                              : SelectItems(
                                                  label: '合格', value: '1'),
                                      top: 0,
                                      selectList: [
                                        SelectItems(label: '合格', value: '1'),
                                        SelectItems(label: '不合格', value: '2')
                                      ],
                                      selectCallback: (item) {
                                        this.setState(() {
                                          workList[index]['selectType'] = item;
                                        });
                                      },
                                      title: '',
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                if (this.justifyInfo()) {
                  showDialog(
                      barrierDismissible: false,
                      context: this.context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('确认提交吗？'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "取消",
                                  style: TextStyle(color: Colors.black),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                  this.addImage();
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
